//--------------------------------------------------------------------//
//     此代码由代码生成器自动生成									  //
//	   生成时间 2020-11-12 09:12:30 	                              //
//	   描述：代码生成器
//--------------------------------------------------------------------//

using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using Dapper;
using Newtonsoft.Json.Linq;
using RayD.Core;
using RayD.Repository;
using RayD.Repository.Entites.SystemModule;
using System;
using System.IO;

namespace RayD.App.SystemModule
{
    public class CodeGeneratorApp
    {
        #region 构造函数注入
        private IRepository BaseRepository;
        private ModuleApp _module;
        public CodeGeneratorApp(IRepository repository, ModuleApp module)
        {
            this.BaseRepository = repository;
            this._module = module;
        }
        #endregion

        #region 获取字段配置
        /// <summary>
        /// 获取当前表所有字段默认配置
        /// </summary>
        /// <param name="tableName">当前表名</param>
        /// <returns></returns>
        public List<FieldConfig> GetDefaultFieldList(string tableName)
        {
            List<FieldConfig> res = new List<FieldConfig>();

            var tableFields = this.BaseRepository.GetDBTableFields<DatabaseTableFieldModel>(tableName).ToList();
            foreach (var tableField in tableFields)
            {
                var o = new FieldConfig()
                {
                    //帕斯卡命名转换
                    Name = tableField.f_column.Pascalize(),
                    Remark = tableField.f_remark,
                    FieldType = FieldType.Text,
                    FieldRule = null,
                    FieldStatistical = null,
                    ShowForm = false,
                    ShowGrid = false,
                    ShowQuery = false
                };
                //字段类型
                Type type = MapCommonType(tableField.f_datatype);
                if (type.Equals(typeof(DateTime)))
                {
                    o.FieldType = FieldType.DateTime;
                }
                else if (type.Equals(typeof(int)))
                {
                    o.FieldType = FieldType.Integer;
                }
                else if (type.Equals(typeof(double)) || type.Equals(typeof(decimal)) || type.Equals(typeof(float)))
                {
                    o.FieldType = FieldType.Float;
                }
                //字段统计性
                if (tableField.f_column.Equals("B_ParentId", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.ParentId;
                }
                else if (tableField.f_column.Equals("B_EnabledMark", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.EnabledMark;
                }
                else if (tableField.f_column.Equals("B_DeleteMark", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.DeleteMark;
                }
                else if (tableField.f_column.Equals("B_CreateUserId", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.CreateUserId;
                }
                else if (tableField.f_column.Equals("B_CreateUserName", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.CreateUserName;
                }
                else if (tableField.f_column.Equals("B_CreateDate", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.CreateDate;
                }
                else if (tableField.f_column.Equals("B_ModifyUserId", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.ModifyUserId;
                }
                else if (tableField.f_column.Equals("B_ModifyUserName", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.ModifyUserName;
                }
                else if (tableField.f_column.Equals("B_ModifyDate", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.ModifyDate;
                }
                else if (tableField.f_column.Equals("B_DeleteUserId", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.DeleteUserId;
                }
                else if (tableField.f_column.Equals("B_DeleteUserName", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.DeleteUserName;
                }
                else if (tableField.f_column.Equals("B_DeleteDate", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.DeleteDate;
                }
                else if (tableField.f_column.Equals("B_SortCode", StringComparison.OrdinalIgnoreCase))
                {
                    o.FieldStatistical = FieldStatistical.SortCode;
                }
                //switch (tableField.f_column)
                //{
                //    case "B_ParentId": o.FieldStatistical = FieldStatistical.ParentId; break;
                //    case "B_EnabledMark": o.FieldStatistical = FieldStatistical.EnabledMark; break;
                //    case "B_DeleteMark": o.FieldStatistical = FieldStatistical.DeleteMark; break;
                //    case "B_CreateUserId": o.FieldStatistical = FieldStatistical.CreateUserId; break;
                //    case "B_CreateUserName": o.FieldStatistical = FieldStatistical.CreateUserName; break;
                //    case "B_CreateDate": o.FieldStatistical = FieldStatistical.CreateDate; break;
                //    case "B_ModifyUserId": o.FieldStatistical = FieldStatistical.ModifyUserId; break;
                //    case "B_ModifyUserName": o.FieldStatistical = FieldStatistical.ModifyUserName; break;
                //    case "B_ModifyDate": o.FieldStatistical = FieldStatistical.ModifyDate; break;
                //    case "B_DeleteUserId": o.FieldStatistical = FieldStatistical.DeleteUserId; break;
                //    case "B_DeleteUserName": o.FieldStatistical = FieldStatistical.DeleteUserName; break;
                //    case "B_DeleteDate": o.FieldStatistical = FieldStatistical.DeleteDate; break;
                //    case "B_SortCode": o.FieldStatistical = FieldStatistical.SortCode; break;
                //}
                res.Add(o);
            }

            return res;
        }
        #endregion

        #region 实体层
        /// <summary>
        /// 实体层代码
        /// </summary>
        /// <param name="config">基础配置信息</param>
        /// <param name="isDefaultConfig">是否启用默认字段配置</param>
        /// <param name="isGenerate">是否生成</param>
        /// <returns></returns>
        public string EntityCode(CodeBaseConfigModel config, bool isDefaultConfig, bool isGenerate)
        {
            StringBuilder res = new StringBuilder(200);
            foreach (var item in config.TableNames)
            {
                #region 是否启用默认字段配置
                if (isDefaultConfig)
                {
                    config.FieldList = GetDefaultFieldList(item);
                    config.IsTree = true;
                }
                #endregion

                StringBuilder sb = new StringBuilder(200);
                //根据表名获取表和表字段信息
                var table = this.BaseRepository.GetDBTable<DatabaseTableModel>()?.FirstOrDefault(c => c.name.Equals(item, StringComparison.OrdinalIgnoreCase));
                var tableFields = this.BaseRepository.GetDBTableFields<DatabaseTableFieldModel>(item).ToList();
                //是否为树型结构
                bool isTree = (config.IsTree && config.FieldList.Exists(c => c.FieldStatistical.Equals(FieldStatistical.ParentId)));
                //是否存在虚拟删除
                var VirtualDelField = config.FieldList.Find(c => c.FieldStatistical.Equals(FieldStatistical.DeleteMark));
                bool isVirtualDel = !VirtualDelField.IsEmpty();

                #region 帕斯卡命名转换
                string tableName = item.Pascalize();
                table.pk = table.pk.Pascalize();
                foreach (var field in tableFields)
                {
                    //帕斯卡命名转换
                    field.f_column = field.f_column.Pascalize();
                }
                #endregion

                sb.Append("//--------------------------------------------------------------------//\r\n");
                sb.Append("//	   此代码由代码生成器自动生成									  //\r\n");
                sb.Append($"//	   生成时间 {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 	                              //\r\n");
                sb.Append($"//	   描述：{table.tdescription}\r\n");
                sb.Append("//--------------------------------------------------------------------//\r\n\r\n");

                #region using
                sb.Append("using System;\r\n");
                sb.Append("using System.ComponentModel.DataAnnotations;\r\n");
                sb.Append("using System.ComponentModel.DataAnnotations.Schema;\r\n");
                sb.Append($"using {Define.CORE_PROJNAME};\r\n");
                sb.Append($"using {Define.REPOSITORY_PROJNAME}.Core;\r\n\r\n");
                #endregion

                sb.Append($"namespace {Define.REPOSITORY_PROJNAME}.Entites.{config.Module}\r\n");
                sb.Append("{\r\n");
                sb.Append($"    [Table(\"{ tableName.ToUpper() }\")] \r\n");
                sb.Append($"    public class { tableName }Entity ");
                //树型继承
                if (isTree) sb.Append($": BaseTreeModel<{ tableName }Entity>");
                sb.Append("\r\n");

                sb.Append("    {\r\n");

                #region 实体成员
                sb.Append("        #region 实体成员\r\n");
                foreach (var field in tableFields)
                {
                    //数据类型
                    string datatype = MapCsharpType(field.f_datatype);
                    #region 根据字段统计性确定数据类型
                    var statistical = config.FieldList.Find(c => c.Name.Equals(field.f_column))?.FieldStatistical;
                    if (statistical.Equals(FieldStatistical.EnabledMark))
                    {
                        datatype = "EnabledMark";
                    }
                    else if (statistical.Equals(FieldStatistical.DeleteMark))
                    {
                        datatype = "DeleteMark";
                    }
                    #endregion
                    //可空标志符号
                    var dataComType = MapCommonType(field.f_datatype);
                    string nullSymbol = (dataComType.IsValueType && field.f_isnullable == "1") ? "?" : "";

                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// " + field.f_remark + "\r\n");
                    sb.Append("        /// </summary>\r\n");
                    sb.Append("        /// <returns></returns>\r\n");
                    if (field.f_key == "1") //是主键
                    {
                        sb.Append("        [Key] \r\n");
                    }
                    sb.Append($"        [Column(\"{field.f_column.ToUpper()}\")] \r\n");
                    sb.Append($"        public { datatype + nullSymbol } { field.f_column } {{ get; set; }}\r\n");
                }
                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 扩展操作
                sb.Append("        #region 扩展操作\r\n");

                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// 新增调用\r\n");
                sb.Append("        /// </summary>\r\n");
                sb.Append("        public void Create()\r\n");
                sb.Append("        {\r\n");
                sb.Append("            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;\r\n");
                foreach (var field in tableFields)
                {
                    //根据字段统计性配置
                    var statistical = config.FieldList.Find(c => c.Name.Equals(field.f_column))?.FieldStatistical;
                    if (field.f_key == "1") //是主键
                    {
                        sb.Append($"            this.{field.f_column} = Guid.NewGuid().ToString();\r\n");
                    }
                    else if (isTree && statistical.Equals(FieldStatistical.ParentId))//是否树型结构
                    {
                        sb.Append($"            if (this.{field.f_column}.IsEmpty())\r\n");
                        sb.Append("            {\r\n");
                        sb.Append($"                this.{field.f_column} = \"0\";\r\n");
                        sb.Append("            }\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.EnabledMark))//使能
                    {
                        sb.Append($"            if (this.{field.f_column}.IsEmpty())\r\n");
                        sb.Append("            {\r\n");
                        sb.Append($"                this.{field.f_column} = EnabledMark.Enabled;\r\n");
                        sb.Append("            }\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.DeleteMark))//是否存在虚拟删除
                    {
                        sb.Append($"            this.{field.f_column} = DeleteMark.Undeleted;\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.CreateUserId))
                    {
                        sb.Append($"            this.{field.f_column} = userInfo.userId;\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.CreateUserName))
                    {
                        sb.Append($"            this.{field.f_column} = userInfo.realName;\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.CreateDate))
                    {
                        sb.Append($"            this.{field.f_column} = DateTime.Now.ToCstTime();\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.ModifyUserId))
                    {
                        sb.Append($"            this.{field.f_column} = userInfo.userId;\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.ModifyUserName))
                    {
                        sb.Append($"            this.{field.f_column} = userInfo.realName;\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.ModifyDate))
                    {
                        sb.Append($"            this.{field.f_column} = DateTime.Now.ToCstTime();\r\n");
                    }
                }
                sb.Append("        }\r\n");



                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// 编辑调用\r\n");
                sb.Append("        /// </summary>\r\n");
                sb.Append("        public void Modify()\r\n");
                sb.Append("        {\r\n");
                sb.Append("            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;\r\n");
                foreach (var field in tableFields)
                {
                    //根据字段统计性配置
                    var statistical = config.FieldList.Find(c => c.Name.Equals(field.f_column))?.FieldStatistical;
                    if (isTree && statistical.Equals(FieldStatistical.ParentId))//是否树型结构
                    {
                        sb.Append($"            if (this.{field.f_column}.IsEmpty())\r\n");
                        sb.Append("            {\r\n");
                        sb.Append($"                this.{field.f_column} = \"0\";\r\n");
                        sb.Append("            }\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.ModifyUserId))
                    {
                        sb.Append($"            this.{field.f_column} = userInfo.userId;\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.ModifyUserName))
                    {
                        sb.Append($"            this.{field.f_column} = userInfo.realName;\r\n");
                    }
                    else if (statistical.Equals(FieldStatistical.ModifyDate))
                    {
                        sb.Append($"            this.{field.f_column} = DateTime.Now.ToCstTime();\r\n");
                    }
                }
                sb.Append("        }\r\n");



                if (isVirtualDel)
                {
                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// 虚拟删除调用\r\n");
                    sb.Append("        /// </summary>\r\n");
                    sb.Append("        public void Delete()\r\n");
                    sb.Append("        {\r\n");
                    sb.Append("            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;\r\n");
                    foreach (var field in tableFields)
                    {
                        //根据字段统计性配置
                        var statistical = config.FieldList.Find(c => c.Name.Equals(field.f_column))?.FieldStatistical;
                        if (statistical.Equals(FieldStatistical.EnabledMark))
                        {
                            sb.Append($"            this.{field.f_column} = EnabledMark.Disabled;\r\n");
                        }
                        else if (statistical.Equals(FieldStatistical.DeleteMark))
                        {
                            sb.Append($"            this.{field.f_column} = DeleteMark.Deleted;\r\n");
                        }
                        else if (statistical.Equals(FieldStatistical.DeleteUserId))
                        {
                            sb.Append($"            this.{field.f_column} = userInfo.userId;\r\n");
                        }
                        else if (statistical.Equals(FieldStatistical.DeleteUserName))
                        {
                            sb.Append($"            this.{field.f_column} = userInfo.realName;\r\n");
                        }
                        else if (statistical.Equals(FieldStatistical.DeleteDate))
                        {
                            sb.Append($"            this.{field.f_column} = DateTime.Now.ToCstTime();\r\n");
                        }
                    }
                    sb.Append("        }\r\n");
                }

                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 树型配置
                if (isTree)
                {
                    sb.Append("        #region 树型配置\r\n");
                    sb.Append("        [NotMapped]\r\n");
                    sb.Append($"        public override string id {{ get => this.{table.pk}; }}\r\n");
                    sb.Append("        [NotMapped]\r\n");
                    sb.Append($"        public override string parentId {{ get => this.{VirtualDelField}; }}\r\n");
                    sb.Append("        [NotMapped]\r\n");
                    sb.Append($"        public override string value {{ get => this.{table.pk}; }}\r\n");
                    sb.Append("        [NotMapped]\r\n");
                    sb.Append("        public override string label {{ get => \"未配置label\"; }}\r\n");
                    sb.Append("        #endregion\r\n");
                }
                #endregion

                sb.Append("    }\r\n");
                sb.Append("}\r\n\r\n");

                #region 代码生成
                if (isGenerate)
                {
                    //项目文件根路径
                    string _contentRoot = Directory.GetParent(Environment.CurrentDirectory).FullName;
                    //输出文件全路径
                    string _contentDir = _contentRoot + Path.DirectorySeparatorChar + Define.REPOSITORY_PROJNAME + Path.DirectorySeparatorChar + "Entites" + Path.DirectorySeparatorChar + config.Module + Path.DirectorySeparatorChar + config.AppDomain + Path.DirectorySeparatorChar + tableName + "Entity.cs";
                    DirFileHelper.CreateFileContent(_contentDir, sb.ToString());
                }
                #endregion

                res.Append(sb);
            }
            return res.ToString();
        }
        #endregion

        #region 应用层
        /// <summary>
        /// 应用层代码
        /// </summary>
        /// <param name="config"></param>
        /// <param name="isGenerate"></param>
        /// <returns></returns>
        public string AppCode(CodeBaseConfigModel config, bool isGenerate)
        {
            StringBuilder res = new StringBuilder(200);
            foreach (var item in config.TableNames)
            {
                StringBuilder sb = new StringBuilder(200);
                //根据表名获取表和表字段信息
                var table = this.BaseRepository.GetDBTable<DatabaseTableModel>()?.FirstOrDefault(c => c.name.Equals(item, StringComparison.OrdinalIgnoreCase));
                //是否为树型结构
                bool isTree = (config.IsTree && config.FieldList.Exists(c => c.FieldStatistical.Equals(FieldStatistical.ParentId)));
                //是否存在虚拟删除
                bool isVirtualDel = (config.FieldList.Exists(c => c.FieldStatistical.Equals(FieldStatistical.DeleteMark)));
                //是否存在使能标志
                var EnabledMarkField = config.FieldList.Find(c => c.FieldStatistical.Equals(FieldStatistical.EnabledMark));
                bool isEnabledMark = !EnabledMarkField.IsEmpty();

                #region 帕斯卡命名转换
                string tableName = item.Pascalize();
                table.pk = table.pk.Pascalize();
                #endregion

                #region 查询条件
                StringBuilder query = new StringBuilder(200);
                query.Append("            var queryParam = queryJson.ToJObject();\r\n");
                foreach (var field in config.FieldList)
                {
                    if (field.ShowQuery)
                    {
                        switch (field.FieldType)
                        {
                            case FieldType.DateTime:
                                query.Append($"            if (!queryParam[\"{field.Name}\"].IsEmpty())\r\n");
                                query.Append("            {\r\n");
                                query.Append($"                expression = expression.And(c => c.{field.Name} >= queryParam[\"{field.Name}\"][0].ToDate() && c.{field.Name} <= queryParam[\"{field.Name}\"][1].ToDate());\r\n");
                                query.Append("            }\r\n");
                                break;
                            case FieldType.Integer:
                                query.Append($"            if (!queryParam[\"{field.Name}\"].IsEmpty())\r\n");
                                query.Append("            {\r\n");
                                query.Append($"                expression = expression.And(c => c.{field.Name} == queryParam[\"{field.Name}\"].ToInt());\r\n");
                                query.Append("            }\r\n");
                                break;
                            default:
                                query.Append($"            if (!queryParam[\"{field.Name}\"].IsEmpty())\r\n");
                                query.Append("            {\r\n");
                                query.Append($"                expression = expression.And(c => c.{field.Name}.Contains(queryParam[\"{field.Name}\"].ToString()));\r\n");
                                query.Append("            }\r\n");
                                break;
                        }
                    }
                }
                //不分页快速查询
                if (!config.IsPage)
                {
                    string queryfield = string.Empty;
                    foreach (var field in config.FieldList)
                    {
                        if (field.ShowGrid)
                        {
                            queryfield += $"                    c.{field.Name}.Contains(queryParam[\"QueryInfo\"].ToString()) ||\r\n";
                        }
                    }
                    queryfield = CommonHelper.DelLastChar(queryfield, "||");

                    if (!queryfield.IsEmpty())
                    {
                        query.Append($"            if (!queryParam[\"QueryInfo\"].IsEmpty())\r\n");
                        query.Append("            {\r\n");
                        query.Append("                expression = expression.And(c => \r\n");
                        query.Append(queryfield);
                        query.Append("                );\r\n");
                        query.Append("            }\r\n");
                    }
                }
                #endregion

                sb.Append("//--------------------------------------------------------------------//\r\n");
                sb.Append("//	   此代码由代码生成器自动生成									  //\r\n");
                sb.Append($"//	   生成时间 {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 	                              //\r\n");
                sb.Append($"//	   描述：{table.tdescription}\r\n");
                sb.Append("//--------------------------------------------------------------------//\r\n\r\n");

                #region using
                sb.Append("using System.Collections.Generic;\r\n");
                sb.Append("using System.Text;\r\n");
                sb.Append("using System.Data;\r\n");
                sb.Append("using System.Linq;\r\n");
                sb.Append("using Dapper;\r\n");
                sb.Append("using Newtonsoft.Json.Linq;\r\n");
                sb.Append($"using {Define.CORE_PROJNAME};\r\n");
                sb.Append($"using {Define.REPOSITORY_PROJNAME};\r\n");
                sb.Append($"using {Define.REPOSITORY_PROJNAME}.Core;\r\n");
                sb.Append($"using {Define.REPOSITORY_PROJNAME}.Entites.{config.Module};\r\n\r\n");
                #endregion

                sb.Append($"namespace {Define.APP_PROJNAME}.{config.Module}\r\n");
                sb.Append("{\r\n");
                sb.Append($"    public class {config.AppDomain}App \r\n");
                sb.Append("    {\r\n");

                #region 构造函数注入
                sb.Append("        #region 构造函数注入\r\n");
                sb.Append("        private IRepository BaseRepository;\r\n");
                sb.Append($"        public {config.AppDomain}App(IRepository repository)\r\n");
                sb.Append("        {\r\n");
                sb.Append("            this.BaseRepository = repository;\r\n");
                sb.Append("        }\r\n");
                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 获取数据
                sb.Append("        #region 获取数据\r\n");
                if (isTree)
                {
                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// 获取树型列表数据\r\n");
                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// <param name=\"queryJson\">查询参数</param>\r\n");
                    sb.Append("        /// <returns></returns>\r\n");
                    sb.Append($"        public IEnumerable<{tableName}Entity> GetTreeList( string queryJson )\r\n");
                    sb.Append("        {\r\n");
                    sb.Append($"            var expression = LinqExtensions.True<{tableName}Entity>();\r\n");
                    sb.Append($"{query}");
                    sb.Append("            return this.BaseRepository.IQueryable(expression).ToTree();\r\n");
                    sb.Append("        }\r\n");
                    if (config.IsPage)
                    {
                        sb.Append("        /// <summary>\r\n");
                        sb.Append("        /// 获取分页列表数据\r\n");
                        sb.Append("        /// </summary>\r\n");
                        sb.Append("        /// <param name=\"queryJson\">查询条件</param>\r\n");
                        sb.Append("        /// <param name=\"pagination\">分页参数</param>\r\n");
                        sb.Append("        /// <returns></returns>\r\n");
                        sb.Append($"        public IEnumerable<{tableName}Entity> GetPageList(string queryJson, Pagination pagination)\r\n");
                        sb.Append("        {\r\n");
                        sb.Append($"            var expression = LinqExtensions.True<{tableName}Entity>();\r\n");
                        sb.Append($"{query}");
                        sb.Append("            var list = this.BaseRepository.IQueryable(expression)\r\n");
                        sb.Append("                        .OrderBy(pagination.sidx, pagination.sord)\r\n");
                        sb.Append("                        .ToTree();\r\n");
                        sb.Append("            /***********************分页处理*********************/\r\n");
                        sb.Append("            var rowsData = list.Skip(pagination.pageSize * (pagination.currentPage - 1)).Take(pagination.pageSize);\r\n");
                        sb.Append("            pagination.records = list.Count();\r\n");
                        sb.Append("\r\n");
                        sb.Append("            return rowsData;\r\n");
                        sb.Append("        }\r\n");
                    }
                }
                else
                {
                    if (config.IsPage)
                    {
                        sb.Append("        /// <summary>\r\n");
                        sb.Append("        /// 获取分页列表数据\r\n");
                        sb.Append("        /// </summary>\r\n");
                        sb.Append("        /// <param name=\"queryJson\">查询条件</param>\r\n");
                        sb.Append("        /// <param name=\"pagination\">分页参数</param>\r\n");
                        sb.Append("        /// <returns></returns>\r\n");
                        sb.Append($"        public IEnumerable<{tableName}Entity> GetPageList(string queryJson, Pagination pagination)\r\n");
                        sb.Append("        {\r\n");
                        sb.Append($"            var expression = LinqExtensions.True<{tableName}Entity>();\r\n");
                        sb.Append($"{query}");
                        sb.Append("            return this.BaseRepository.FindList(expression, pagination);\r\n");
                        sb.Append("        }\r\n");
                    }
                    else
                    {
                        sb.Append("        /// <summary>\r\n");
                        sb.Append("        /// 获取列表数据\r\n");
                        sb.Append("        /// <summary>\r\n");
                        sb.Append("        /// <param name=\"queryJson\">查询参数</param>\r\n");
                        sb.Append("        /// <returns></returns>\r\n");
                        sb.Append($"        public IEnumerable<{tableName}Entity> GetList( string queryJson )\r\n");
                        sb.Append("        {\r\n");
                        sb.Append($"            var expression = LinqExtensions.True<{tableName}Entity>();\r\n");
                        sb.Append($"{query}");
                        sb.Append("            return this.BaseRepository.IQueryable(expression);\r\n");
                        sb.Append("        }\r\n");
                    }
                }
                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 提交数据
                sb.Append("        #region 提交数据\r\n");

                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// 保存实体数据（新增、修改）\r\n");
                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// <param name=\"formEntity\">数据实体</param>\r\n");
                sb.Append("        /// <returns></returns>\r\n");
                sb.Append("        [RemoveCache]\r\n");
                sb.Append($"        public virtual (bool, string) SaveForm({tableName}Entity formEntity)\r\n");
                sb.Append("        {\r\n");
                sb.Append($"            if (!formEntity.{table.pk}.IsEmpty())\r\n");
                sb.Append("            {\r\n");
                sb.Append("                //编辑(Null、主键不会更改)\r\n");
                sb.Append("                formEntity.Modify();\r\n");
                sb.Append("                this.BaseRepository.Update(formEntity);\r\n");
                sb.Append("            }\r\n");
                sb.Append("            else\r\n");
                sb.Append("            {\r\n");
                sb.Append("                //新增\r\n");
                sb.Append("                formEntity.Create();\r\n");
                sb.Append("                this.BaseRepository.Insert(formEntity);\r\n");
                sb.Append("            }\r\n");
                sb.Append("            return (true, \"保存成功！\");\r\n");
                sb.Append("        }\r\n");

                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// 删除实体数据\r\n");
                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// <param name=\"formEntity\">数据实体</param>\r\n");
                sb.Append("        /// <returns></returns>\r\n");
                sb.Append("        [RemoveCache]\r\n");
                sb.Append($"        public virtual (bool, string) DeleteForm({tableName}Entity formEntity)\r\n");
                sb.Append("        {\r\n");
                if (isVirtualDel)
                {
                    sb.Append($"            var entity = this.BaseRepository.FindEntity<{tableName}Entity>(formEntity.{table.pk});\r\n");
                    sb.Append("            if (!entity.IsEmpty())\r\n");
                    sb.Append("            {\r\n");
                    sb.Append("                entity.Delete();\r\n");
                    sb.Append("                this.BaseRepository.Update(entity);\r\n");
                    sb.Append("                return (true, \"删除成功！\");\r\n");
                    sb.Append("            }\r\n");
                    sb.Append("            else\r\n");
                    sb.Append("            {\r\n");
                    sb.Append("                return (true, \"删除失败！\");\r\n");
                    sb.Append("            }\r\n");
                }
                else
                {
                    sb.Append("            this.BaseRepository.Delete(formEntity);\r\n");
                    sb.Append("            return (true, \"删除成功！\");\r\n");
                }
                sb.Append("        }\r\n");

                if (isEnabledMark)
                {
                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// 状态更改\r\n");
                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// <param name=\"formEntity\">数据实体</param>\r\n");
                    sb.Append("        /// <returns></returns>\r\n");
                    sb.Append("        [RemoveCache]\r\n");
                    sb.Append($"        public virtual (bool, string) ChangeState({tableName}Entity formEntity)\r\n");
                    sb.Append("        {\r\n");
                    sb.Append($"            if (!formEntity.{table.pk}.IsEmpty())\r\n");
                    sb.Append("            {\r\n");
                    sb.Append($"                this.BaseRepository.Update(new {tableName}Entity() {{ {table.pk} = formEntity.{table.pk}, {EnabledMarkField.Name} = formEntity.{EnabledMarkField.Name} }});\r\n");
                    sb.Append("                return (true, \"更改成功！\");\r\n");
                    sb.Append("            }\r\n");
                    sb.Append("            else\r\n");
                    sb.Append("            {\r\n");
                    sb.Append("                return (false, \"更改失败！\");\r\n");
                    sb.Append("            }\r\n");
                    sb.Append("        }\r\n");
                }
                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 数据验证
                sb.Append("        #region 数据验证\r\n");
                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// 验证字段值是否存在\r\n");
                sb.Append("        /// </summary>\r\n");
                sb.Append("        /// <param name=\"id\">实体主键</param>\r\n");
                sb.Append("        /// <param name=\"field\">字段名</param>\r\n");
                sb.Append("        /// <param name=\"value\">字段值</param>\r\n");
                sb.Append("        /// <returns></returns>\r\n");
                sb.Append("        public bool ValidateExist(string id, string field, string value)\r\n");
                sb.Append("        {\r\n");
                sb.Append($"            var expression = LinqExtensions.True<{tableName}Entity>();\r\n");
                sb.Append("            if (!string.IsNullOrEmpty(id))\r\n");
                sb.Append("            {\r\n");
                sb.Append($"                expression = expression.And(t => t.{table.pk} != id);\r\n");
                sb.Append("            }\r\n");
                sb.Append("            return this.BaseRepository.IQueryable(expression).Exist(field, value);\r\n");
                sb.Append("        }\r\n");
                sb.Append("        #endregion\r\n");
                #endregion

                sb.Append("    }\r\n");
                sb.Append("}\r\n");

                #region 代码生成
                if (isGenerate)
                {
                    //项目文件根路径
                    string _contentRoot = Directory.GetParent(Environment.CurrentDirectory).FullName;
                    //输出文件全路径
                    string _contentDir = _contentRoot + Path.DirectorySeparatorChar + Define.APP_PROJNAME + Path.DirectorySeparatorChar + config.Module + Path.DirectorySeparatorChar + config.AppDomain + "App.cs";
                    DirFileHelper.CreateFileContent(_contentDir, sb.ToString());
                }
                #endregion

                res.Append(sb);
            }
            return res.ToString();
        }

        #endregion

        #region 表现层
        /// <summary>
        /// 表现层代码
        /// </summary>
        /// <param name="config"></param>
        /// <param name="isGenerate"></param>
        /// <returns></returns>
        public string ControllerCode(CodeBaseConfigModel config, bool isGenerate)
        {
            StringBuilder res = new StringBuilder(200);
            foreach (var item in config.TableNames)
            {
                StringBuilder sb = new StringBuilder(200);
                //帕斯卡命名转换
                string tableName = item.Pascalize();
                //根据表名获取表和表字段信息
                var table = this.BaseRepository.GetDBTable<DatabaseTableModel>()?.FirstOrDefault(c => c.name.Equals(tableName, StringComparison.OrdinalIgnoreCase));
                //是否为树型结构
                bool isTree = (config.IsTree && config.FieldList.Exists(c => c.FieldStatistical.Equals(FieldStatistical.ParentId)));
                //是否存在使能标志
                var EnabledMarkField = config.FieldList.Find(c => c.FieldStatistical.Equals(FieldStatistical.EnabledMark));
                bool isEnabledMark = !EnabledMarkField.IsEmpty();

                sb.Append("//--------------------------------------------------------------------//\r\n");
                sb.Append("//	   此代码由代码生成器自动生成									  //\r\n");
                sb.Append($"//	   生成时间 {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 	                              //\r\n");
                sb.Append($"//	   描述：{table.tdescription}\r\n");
                sb.Append("//--------------------------------------------------------------------//\r\n\r\n");

                #region using
                sb.Append("using Microsoft.AspNetCore.Mvc;\r\n");
                sb.Append("using Microsoft.AspNetCore.StaticFiles;\r\n");
                sb.Append("using System.Collections.Generic;\r\n");
                sb.Append("using System.IO;\r\n");
                sb.Append("using System.Data;\r\n");
                sb.Append($"using {Define.APP_PROJNAME}.{config.Module};\r\n");
                sb.Append($"using {Define.REPOSITORY_PROJNAME}.Core;\r\n");
                sb.Append($"using {Define.REPOSITORY_PROJNAME}.Entites.{config.Module};\r\n");
                sb.Append($"using {Define.CORE_PROJNAME};\r\n\r\n");
                #endregion

                sb.Append($"namespace {Define.WEBAPI_PROJNAME}.Controllers.{config.Area}\r\n");
                sb.Append("{\r\n");
                sb.Append($"    public class {config.AppDomain}Controller : Base{config.Area}Controller\r\n");
                sb.Append("    {\r\n");

                #region 构造函数注入
                sb.Append("        #region 构造函数注入\r\n");
                sb.Append($"        private {config.AppDomain}App _{config.AppDomain}App;\r\n");
                sb.Append($"        public {config.AppDomain}Controller({config.AppDomain}App {config.AppDomain}App)\r\n");
                sb.Append("        {\r\n");
                sb.Append($"            this._{config.AppDomain}App = {config.AppDomain}App;\r\n");
                sb.Append("        }\r\n");
                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 请求参数
                sb.Append("        #region 请求参数\r\n");
                if (config.IsPage)
                {
                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// 分页数据查询响应参数\r\n");
                    sb.Append("        /// </summary>\r\n");
                    sb.Append("        public class GetPageRespone\r\n");
                    sb.Append("        {\r\n");
                    sb.Append("            /// <summary>\r\n");
                    sb.Append("            /// 查询响应数据\r\n");
                    sb.Append("            /// </summary>\r\n");
                    sb.Append($"            public IEnumerable<{tableName}Entity> rows {{ get; set; }}\r\n");
                    sb.Append("            /// <summary>\r\n");
                    sb.Append("            /// 总记录数\r\n");
                    sb.Append("            /// </summary>\r\n");
                    sb.Append("            public int records { get; set; }\r\n");
                    sb.Append("        }\r\n");
                }
                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 获取数据
                sb.Append("        #region 获取数据\r\n");
                if (isTree)
                {
                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// 获取树型列表数据\r\n");
                    sb.Append("        /// </summary>\r\n");
                    sb.Append("        /// <param name=\"queryjson\">查询参数</param>\r\n");
                    sb.Append("        /// <returns></returns>\r\n");
                    sb.Append("        [HttpGet]\r\n");
                    sb.Append($"        public ResParameter<IEnumerable<{tableName}Entity>> GetTreeList(string queryjson)\r\n");
                    sb.Append("        {\r\n");
                    sb.Append($"            var list = _{config.AppDomain}App.GetTreeList(queryjson);\r\n");
                    sb.Append("            return Success(list);\r\n");
                    sb.Append("        }\r\n");
                    if (config.IsPage)
                    {
                        sb.Append("        /// <summary>\r\n");
                        sb.Append("        /// 获取分页列表数据\r\n");
                        sb.Append("        /// </summary>\r\n");
                        sb.Append("        /// <param name=\"queryjson\">查询参数</param>\r\n");
                        sb.Append("        /// <param name=\"pagination\">分页参数</param>\r\n");
                        sb.Append("        /// <returns></returns>\r\n");
                        sb.Append("        [HttpGet]\r\n");
                        sb.Append("        public ResParameter<GetPageRespone> GetPageList(string queryjson, string pagination)\r\n");
                        sb.Append("        {\r\n");
                        sb.Append("            var paginationObj = pagination.ToObject<Pagination>();\r\n");
                        sb.Append($"            var data = _{config.AppDomain}App.GetPageList(queryjson, paginationObj);\r\n");
                        sb.Append("            return Success(new GetPageRespone()\r\n");
                        sb.Append("            {\r\n");
                        sb.Append("                rows = data,\r\n");
                        sb.Append("                records = paginationObj.records\r\n");
                        sb.Append("            });\r\n");
                        sb.Append("        }\r\n");
                    }
                }
                else
                {
                    if (config.IsPage)
                    {
                        sb.Append("        /// <summary>\r\n");
                        sb.Append("        /// 获取分页列表数据\r\n");
                        sb.Append("        /// </summary>\r\n");
                        sb.Append("        /// <param name=\"queryjson\">查询参数</param>\r\n");
                        sb.Append("        /// <param name=\"pagination\">分页参数</param>\r\n");
                        sb.Append("        /// <returns></returns>\r\n");
                        sb.Append("        [HttpGet]\r\n");
                        sb.Append("        public ResParameter<GetPageRespone> GetPageList(string queryjson, string pagination)\r\n");
                        sb.Append("        {\r\n");
                        sb.Append("            var paginationObj = pagination.ToObject<Pagination>();\r\n");
                        sb.Append($"            var data = _{config.AppDomain}App.GetPageList(queryjson, paginationObj);\r\n");
                        sb.Append("            return Success(new GetPageRespone()\r\n");
                        sb.Append("            {\r\n");
                        sb.Append("                rows = data,\r\n");
                        sb.Append("                records = paginationObj.records\r\n");
                        sb.Append("            });\r\n");
                        sb.Append("        }\r\n");
                    }
                    else
                    {
                        sb.Append("        /// <summary>\r\n");
                        sb.Append("        /// 获取列表数据\r\n");
                        sb.Append("        /// </summary>\r\n");
                        sb.Append("        /// <param name=\"queryjson\">查询参数</param>\r\n");
                        sb.Append("        /// <returns></returns>\r\n");
                        sb.Append("        [HttpGet]\r\n");
                        sb.Append($"        public ResParameter<IEnumerable<{tableName}Entity>> GetList(string queryjson)\r\n");
                        sb.Append("        {\r\n");
                        sb.Append($"            var list = _{config.AppDomain}App.GetList(queryjson);\r\n");
                        sb.Append("            return Success(list);\r\n");
                        sb.Append("        }\r\n");
                    }
                }
                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 提交数据
                sb.Append("        #region 提交数据\r\n");

                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// 保存实体(新增,编辑)\r\n");
                sb.Append("        /// </summary>\r\n");
                sb.Append("        /// <param name=\"request\">实体</param>\r\n");
                sb.Append("        /// <returns></returns>\r\n");
                sb.Append($"        [HttpPut, Logging(\"{table.tdescription}保存\")]\r\n");
                sb.Append($"        public ResParameter SaveForm({tableName}Entity request)\r\n");
                sb.Append("        {\r\n");
                sb.Append($"            var (isSuccess, msg) = _{config.AppDomain}App.SaveForm(request);\r\n");
                sb.Append("            if (isSuccess)\r\n");
                sb.Append("            {\r\n");
                sb.Append("                return Success(msg);\r\n");
                sb.Append("            }\r\n");
                sb.Append("            else\r\n");
                sb.Append("            {\r\n");
                sb.Append("                return Fail(msg);\r\n");
                sb.Append("            }\r\n");
                sb.Append("        }\r\n");

                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// 删除实体\r\n");
                sb.Append("        /// </summary>\r\n");
                sb.Append("        /// <param name=\"request\">实体</param>\r\n");
                sb.Append("        /// <returns></returns>\r\n");
                sb.Append($"        [HttpPut, Logging(\"{table.tdescription}删除\")]\r\n");
                sb.Append($"        public ResParameter DeleteForm({tableName}Entity request)\r\n");
                sb.Append("        {\r\n");
                sb.Append($"            var (isSuccess, msg) = _{config.AppDomain}App.DeleteForm(request);\r\n");
                sb.Append("            if (isSuccess)\r\n");
                sb.Append("            {\r\n");
                sb.Append("                return Success(msg);\r\n");
                sb.Append("            }\r\n");
                sb.Append("            else\r\n");
                sb.Append("            {\r\n");
                sb.Append("                return Fail(msg);\r\n");
                sb.Append("            }\r\n");
                sb.Append("        }\r\n");

                if (isEnabledMark)
                {
                    sb.Append("        /// <summary>\r\n");
                    sb.Append("        /// 状态更改\r\n");
                    sb.Append("        /// </summary>\r\n");
                    sb.Append("        /// <param name=\"request\">实体</param>\r\n");
                    sb.Append("        /// <returns></returns>\r\n");
                    sb.Append($"        [HttpPut, Logging(\"{table.tdescription}状态更改\")]\r\n");
                    sb.Append($"        public ResParameter ChangeState({tableName}Entity request)\r\n");
                    sb.Append("        {\r\n");
                    sb.Append($"            var (isSuccess, msg) = _{config.AppDomain}App.ChangeState(request);\r\n");
                    sb.Append("            if (isSuccess)\r\n");
                    sb.Append("            {\r\n");
                    sb.Append("                return Success(msg);\r\n");
                    sb.Append("            }\r\n");
                    sb.Append("            else\r\n");
                    sb.Append("            {\r\n");
                    sb.Append("                return Fail(msg);\r\n");
                    sb.Append("            }\r\n");
                    sb.Append("        }\r\n");
                }
                sb.Append("        #endregion\r\n\r\n");
                #endregion

                #region 数据验证
                sb.Append("        #region 数据验证\r\n");
                sb.Append("        /// <summary>\r\n");
                sb.Append("        /// 验证字段值是否存在\r\n");
                sb.Append("        /// </summary>\r\n");
                sb.Append("        /// <param name=\"id\">实体主键</param>\r\n");
                sb.Append("        /// <param name=\"field\">字段名</param>\r\n");
                sb.Append("        /// <param name=\"value\">字段值</param>\r\n");
                sb.Append("        /// <returns></returns>\r\n");
                sb.Append("        [HttpGet]\r\n");
                sb.Append("        public ResParameter ValidateExist(string id, string field, string value)\r\n");
                sb.Append("        {\r\n");
                sb.Append($"            var res = _{config.AppDomain}App.ValidateExist(id, field, value);\r\n");
                sb.Append("            if (!res)\r\n");
                sb.Append("            {\r\n");
                sb.Append("                return Success(\"校验通过\");\r\n");
                sb.Append("            }\r\n");
                sb.Append("            else\r\n");
                sb.Append("            {\r\n");
                sb.Append("                return Fail(\"值已存在，校验不通过！\");\r\n");
                sb.Append("            }\r\n");
                sb.Append("        }\r\n");
                sb.Append("        #endregion\r\n");
                #endregion

                sb.Append("    }\r\n");
                sb.Append("}\r\n");

                #region 代码生成
                if (isGenerate)
                {
                    //项目文件根路径
                    string _contentRoot = Directory.GetParent(Environment.CurrentDirectory).FullName;
                    //输出文件全路径
                    string _contentDir = _contentRoot + Path.DirectorySeparatorChar + Define.WEBAPI_PROJNAME + Path.DirectorySeparatorChar + "Controllers" + Path.DirectorySeparatorChar + config.Area + Path.DirectorySeparatorChar + config.Module + Path.DirectorySeparatorChar + config.AppDomain + "Controller.cs";
                    DirFileHelper.CreateFileContent(_contentDir, sb.ToString());
                }
                #endregion

                res.Append(sb);
            }
            return res.ToString();
        }
        #endregion

        #region 页面
        /// <summary>
        /// 页面代码
        /// TODO: FieldType字段类型扩充
        /// </summary>
        /// <param name="config"></param>
        /// <param name="isGenerate"></param>
        /// <returns></returns>
        public string IndexCode(CodeBaseConfigModel config, bool isGenerate)
        {
            StringBuilder res = new StringBuilder(200);
            foreach (var item in config.TableNames)
            {
                StringBuilder sb = new StringBuilder(200);
                //帕斯卡命名转换
                string tableName = item.Pascalize();
                //根据表名获取表和表字段信息
                var table = this.BaseRepository.GetDBTable<DatabaseTableModel>()?.FirstOrDefault(c => c.name.Equals(tableName, StringComparison.OrdinalIgnoreCase));
                //是否为树型结构
                bool isTree = (config.IsTree && config.FieldList.Exists(c => c.FieldStatistical.Equals(FieldStatistical.ParentId)));
                //是否存在使能标志
                var EnabledMarkField = config.FieldList.Find(c => c.FieldStatistical.Equals(FieldStatistical.EnabledMark));
                bool isEnabledMark = !EnabledMarkField.IsEmpty();

                #region 查询条件
                StringBuilder query = new StringBuilder(200);
                foreach (var field in config.FieldList)
                {
                    if (field.ShowQuery)
                    {
                        query.Append($"           <vxe-form-item title=\"{field.Remark}\">\r\n");
                        switch (field.FieldType)
                        {
                            case FieldType.DateTime:
                                query.Append($"              <rayd-date-picker type=\"datetimerange\" v-model=\"queryEntity.{field.Name}\" />\r\n");
                                break;
                            default:
                                query.Append($"              <el-input v-model=\"queryEntity.{field.Name}\" clearable></el-input>\r\n");
                                break;
                        }
                        query.Append("           </vxe-form-item>\r\n");
                    }
                }
                #endregion

                #region 列表配置
                StringBuilder grid = new StringBuilder(200);
                foreach (var field in config.FieldList)
                {
                    if (field.ShowGrid)
                    {
                        //统计性字段
                        if (field.FieldStatistical.Equals(FieldStatistical.EnabledMark))
                        {
                            grid.Append($"        {{ field: \"{field.Name}\", title: \"{field.Remark}\", sortable: true, slots: {{ default: \" {field.Name}\" }}}},\r\n");
                            continue;
                        }
                        switch (field.FieldType)
                        {
                            case FieldType.DateTime:
                                grid.Append("        {\r\n");
                                grid.Append($"          field: \"{field.Name}\",\r\n");
                                grid.Append($"          title: \"{field.Remark}\",\r\n");
                                grid.Append("          sortable: true,\r\n");
                                grid.Append("          formatter: [\"toDateString\", \"yyyy-MM-dd\"]\r\n");
                                grid.Append("        },\r\n");
                                break;
                            case FieldType.Image:
                                grid.Append("        {\r\n");
                                grid.Append($"          field: \"{field.Name}\",\r\n");
                                grid.Append($"          title: \"{field.Remark}\",\r\n");
                                grid.Append("          width: 200,\r\n");
                                grid.Append("          showOverflow: false,\r\n");
                                grid.Append("          cellRender: { name: 'imgView' },\r\n");
                                grid.Append("        },\r\n");
                                break;
                            default:
                                grid.Append("        {\r\n");
                                grid.Append($"          field: \"{field.Name}\",\r\n");
                                grid.Append($"          title: \"{field.Remark}\",\r\n");
                                grid.Append("          sortable: true,\r\n");
                                grid.Append("        },\r\n");
                                break;
                        }
                    }
                }
                #endregion


                #region 业务按钮
                StringBuilder authBtns = new StringBuilder(200);
                authBtns.Append("        <!-- 业务按钮 -->\r\n");
                authBtns.Append("        <template v-slot:toolbar_buttons>\r\n");
                authBtns.Append("          <el-button round type=\"primary\" icon=\"el-icon-plus\" @click=\"handleAdd\" v-permission-btn=\"'Add'\">新增</el-button>\r\n");
                authBtns.Append("          <el-button round type=\"warning\" icon=\"el-icon-edit\" @click=\"handleEdit\" v-permission-btn=\"'Edit'\">编辑</el-button>\r\n");
                authBtns.Append("          <el-button round type=\"danger\" icon=\"el-icon-delete\" @click=\"handleDelete\" v-permission-btn=\"'Delete'\">删除</el-button>\r\n");
                authBtns.Append("          <el-divider direction=\"vertical\"></el-divider>\r\n");
                authBtns.Append("        </template>\r\n");
                #endregion

                #region 禁用/启用模板
                StringBuilder enableTemplate = new StringBuilder(200);
                if (isEnabledMark)
                {
                    enableTemplate.Append("        <!-- 禁用/启用模板 -->\r\n");
                    enableTemplate.Append($"        <template v-slot:{EnabledMarkField.Name}=\"{{ row }}\">\r\n");
                    enableTemplate.Append("          <vxe-switch v-model=\"row.{EnabledMarkField.Name}\" on-label=\"启用\" :on-value=\"1\" off-label=\"禁用enableTemplate\" :off-value=\"0\" @change=\"ChangeState(row)\"></vxe-switch>\r\n");
                    enableTemplate.Append("        </template>\r\n");
                }
                #endregion

                #region 初始化方法
                StringBuilder init = new StringBuilder(200);
                init.Append("    //初始化\r\n");
                init.Append("    init() {\r\n");
                init.Append("      this.$store.commit(\"SET_ISLOADING\",true);\r\n");
                init.Append("	    /* 初始化数据源 */\r\n");
                init.Append("      Promise.all([]).then(() => {\r\n");
                if (config.IsPage)
                {
                    init.Append("        this.$store.commit(\"SET_ISLOADING\",false);\r\n");
                }
                else
                {
                    init.Append("        this.query();\r\n");
                }
                init.Append("      });\r\n");
                init.Append("    },\r\n");
                #endregion

                #region 状态变更方法
                StringBuilder changeState = new StringBuilder(200);
                if (isEnabledMark)
                {
                    changeState.Append("    //状态变更\r\n");
                    changeState.Append("    ChangeState(row) {\r\n");
                    changeState.Append($"      {config.AppDomain}.ChangeState({{ {table.pk}: row.{table.pk}, {EnabledMarkField.Name}: row.changeState{EnabledMarkField.Name} }}).catch(err => {{\r\n");
                    changeState.Append("        //状态归位\r\n");
                    changeState.Append($"        row.{EnabledMarkField.Name} = !row.{EnabledMarkField.Name};\r\n");
                    changeState.Append("      });\r\n");
                    changeState.Append("    },\r\n");
                }
                #endregion

                #region 增删改方法
                StringBuilder curd = new StringBuilder(200);
                curd.Append("    //新增\r\n");
                curd.Append("    handleAdd() {\r\n");
                curd.Append("      this.$refs[\"mainForm\"].formOpen();\r\n");
                curd.Append("    },\r\n");
                curd.Append("    //编辑\r\n");
                curd.Append("    handleEdit() {\r\n");
                curd.Append("      let row = this.$refs[\"mainTable\"].getCurrentRecord();\r\n");
                curd.Append("      if (row) {\r\n");
                curd.Append("        this.$refs[\"mainForm\"].formOpen(row);\r\n");
                curd.Append("      }else {\r\n");
                curd.Append("        this.$message.warning(\"请选择数据行！\");\r\n");
                curd.Append("      }\r\n");
                curd.Append("    },\r\n");
                curd.Append("    //删除\r\n");
                curd.Append("    handleDelete() {\r\n");
                curd.Append("      let row = this.$refs[\"mainTable\"].getCurrentRecord();\r\n");
                curd.Append("      if (row) {\r\n");
                curd.Append("        this.$confirm(\"确认永久删除该行数据?\", \"提示\", { type: \"warning\" })\r\n");
                curd.Append("          .then(() => {\r\n");
                curd.Append($"            {config.AppDomain}.Delete(row).then(res => {{\r\n");
                if (config.IsPage)
                {
                    curd.Append("              this.$refs[\"mainTable\"].commitProxy(\"reload\"); // 刷新表格\r\n");
                }
                else
                {
                    curd.Append("              this.query(); // 刷新表格\r\n");
                }
                curd.Append("            });\r\n");
                curd.Append("          })\r\n");
                curd.Append("          .catch(e => {});\r\n");
                curd.Append("      }else {\r\n");
                curd.Append("        this.$message.warning(\"请选择数据行！\");\r\n");
                curd.Append("      }\r\n");
                curd.Append("    },\r\n");
                #endregion

                if (config.IsPage)
                {
                    #region Template
                    sb.Append("<template>\r\n");
                    sb.Append("  <el-container>\r\n");
                    sb.Append("    <el-main>\r\n");
                    sb.Append("      <!-- 表格  -->\r\n");
                    sb.Append("      <vxe-grid\r\n");
                    sb.Append("        ref=\"mainTable\"\r\n");
                    sb.Append("        column-key	\r\n");
                    sb.Append("        context-menu\r\n");
                    sb.Append("        v-grid-drag-col\r\n");
                    sb.Append("        :height=\"$store.getters.scrollerHeight()\"\r\n");
                    sb.Append("        :toolbar=\"tableToolbar\"\r\n");
                    sb.Append("        :columns=\"tableColumn\"\r\n");
                    sb.Append("        :proxy-config=\"tableProxy\"\r\n");
                    sb.Append("        :sort-config=\"{remote:true}\"\r\n");
                    sb.Append("        pager-config");
                    if (isTree)
                    {
                        sb.Append("        tree-config");
                    }
                    sb.Append(">\r\n");
                    sb.Append("        <!-- 多条件查询 -->\r\n");
                    sb.Append("        <template v-slot:toolbar_search>\r\n");
                    sb.Append("          <rayd-multi-query\r\n");
                    sb.Append("            v-model=\"queryEntity\"\r\n");
                    sb.Append("            @query=\"$refs[`mainTable`].commitProxy(`reload`)\"\r\n");
                    sb.Append("          >\r\n");
                    sb.Append(query);
                    sb.Append("          </rayd-multi-query>\r\n");
                    sb.Append("        </template>\r\n");
                    sb.Append(authBtns);
                    sb.Append(enableTemplate);
                    sb.Append("      </vxe-grid>\r\n");
                    sb.Append("    </el-main>\r\n");
                    sb.Append("    <!-- 拟态窗口 -->\r\n");
                    sb.Append("    <Form ref=\"mainForm\" @refresh=\"$refs[`mainTable`].commitProxy(`reload`)\" />\r\n");
                    sb.Append("  </el-container>\r\n");
                    sb.Append("</template>\r\n\r\n");
                    #endregion

                    #region Script
                    sb.Append("<script>\r\n");
                    sb.Append($"import {{ {config.AppDomain} }} from \"@/api\";\r\n");
                    sb.Append("import Form from \"./Form.vue\";\r\n");
                    sb.Append("export default {\r\n");
                    sb.Append("  components: { Form },\r\n");
                    sb.Append("  computed: {\r\n");
                    sb.Append("    //列配置\r\n");
                    sb.Append("    tableColumn(){\r\n");
                    sb.Append("      return [\r\n");
                    sb.Append("        {\r\n");
                    sb.Append("          type: \"seq\",\r\n");
                    sb.Append("          title: \"序号\",\r\n");
                    sb.Append("          align: \"left\",\r\n");
                    sb.Append("          width: 80,\r\n");
                    if (isTree)
                    {
                        sb.Append("          treeNode: true\r\n");
                    }
                    sb.Append("        },\r\n");
                    sb.Append(grid);
                    sb.Append("      ];\r\n");
                    sb.Append("    },\r\n");
                    sb.Append("  },\r\n");
                    sb.Append("  data() {\r\n");
                    sb.Append("    return {\r\n");
                    sb.Append("      /* vxe-grid */\r\n");
                    sb.Append("      queryEntity: {}, //查询实体\r\n");
                    sb.Append("      //工具栏配置\r\n");
                    sb.Append("      tableToolbar: {\r\n");
                    sb.Append("        refresh: true,\r\n");
                    sb.Append("        zoom: true,\r\n");
                    sb.Append("        custom: true\r\n");
                    sb.Append("      },\r\n");
                    sb.Append("      //数据代理配置\r\n");
                    sb.Append("      tableProxy: {\r\n");
                    sb.Append("        seq: true, // 启用动态序号代理\r\n");
                    sb.Append("        sort: true, // 启用排序代理\r\n");
                    sb.Append("        autoLoad: false, //是否自动加载查询数据\r\n");
                    sb.Append("        ajax: {\r\n");
                    sb.Append("          // 任何支持 Promise API 的库都可以对接（fetch、jquery、axios、xe-ajax）\r\n");
                    sb.Append("          query: ({ page, sort, filters }) => {\r\n");
                    sb.Append("            page.sidx = sort.property;\r\n");
                    sb.Append("            page.sord = sort.order;\r\n");
                    sb.Append($"            return {config.AppDomain}.GetPageList({{\r\n");
                    sb.Append("              queryjson: JSON.stringify(this.queryEntity),\r\n");
                    sb.Append("              pagination: JSON.stringify(page)\r\n");
                    sb.Append("            }).then(res => {\r\n");
                    sb.Append("              return res;\r\n");
                    sb.Append("            });\r\n");
                    sb.Append("          }\r\n");
                    sb.Append("        }\r\n");
                    sb.Append("      },\r\n");
                    sb.Append("      /* 实体数据 */\r\n");
                    sb.Append("    };\r\n");
                    sb.Append("  },\r\n");
                    sb.Append("  created() {\r\n");
                    sb.Append("    //初始化\r\n");
                    sb.Append("    this.init();\r\n");
                    sb.Append("  },\r\n");
                    sb.Append("  methods: {\r\n");
                    sb.Append(init);
                    sb.Append(changeState);
                    sb.Append(curd);
                    sb.Append("  }\r\n");
                    sb.Append("};\r\n");
                    sb.Append("</script>\r\n");
                    #endregion
                }
                else
                {
                    #region Template
                    sb.Append("<template>\r\n");
                    sb.Append("  <el-container>\r\n");
                    sb.Append("    <el-main>\r\n");
                    sb.Append("     <!-- 表格  -->\r\n");
                    sb.Append("     <vxe-grid\r\n");
                    sb.Append("        ref=\"mainTable\"\r\n");
                    sb.Append("        column-key\r\n");
                    sb.Append("        context-menu\r\n");
                    sb.Append("        v-grid-drag-col\r\n");
                    sb.Append("        :height=\"$store.getters.scrollerHeight()\"\r\n");
                    sb.Append("        :toolbar=\"tableToolbar\"\r\n");
                    sb.Append("        :columns=\"tableColumn\"\r\n");
                    sb.Append("        :data=\"tableData\"\r\n");
                    sb.Append($"        :export-config=\"{{filename:'{table.tdescription}',sheetName:'{table.tdescription}'}}\"\r\n");
                    if (isTree)
                    {
                        sb.Append("        :tree-config=\"{ expandAll: false}\"\r\n");
                    }
                    sb.Append("      >\r\n");
                    sb.Append("        <!-- 快速查询 -->\r\n");
                    sb.Append("        <template v-slot:toolbar_search>\r\n");
                    sb.Append("          <rayd-quick-query v-model=\"filterName\" @query=\"query\"></rayd-quick-query>\r\n");
                    sb.Append("        </template>\r\n");
                    sb.Append(authBtns);
                    sb.Append(enableTemplate);
                    sb.Append("      </vxe-grid>\r\n");
                    sb.Append("    </el-main>\r\n");
                    sb.Append("    <!-- 拟态窗口 -->\r\n");
                    sb.Append("    <Form ref=\"mainForm\" @refresh=\"query()\" />\r\n");
                    sb.Append("  </el-container>\r\n");
                    sb.Append("</template>\r\n\r\n");
                    #endregion

                    #region Script
                    sb.Append("<script>\r\n");
                    sb.Append($"import {{ {config.AppDomain} }} from \"@/api\";\r\n");
                    sb.Append("import Form from \"./Form.vue\";\r\n");
                    sb.Append("export default {\r\n");
                    sb.Append("  components: { Form },\r\n");
                    sb.Append("  computed: {\r\n");
                    sb.Append("     //列配置\r\n");
                    sb.Append("     tableColumn(){\r\n");
                    sb.Append("      return [\r\n");
                    sb.Append("        {\r\n");
                    sb.Append("          type: \"seq\",\r\n");
                    sb.Append("          title: \"序号\",\r\n");
                    sb.Append("          fixed: \"left\",\r\n");
                    sb.Append("          align: \"left\",\r\n");
                    sb.Append("          width: 80,\r\n");
                    if (isTree)
                    {
                        sb.Append("          treeNode: true\r\n");
                    }
                    sb.Append("        },\r\n");
                    sb.Append(grid);
                    sb.Append("      ];\r\n");
                    sb.Append("     },\r\n");
                    sb.Append("  },\r\n");
                    sb.Append("  data() {\r\n");
                    sb.Append("    return {\r\n");
                    sb.Append("      /* vxe-grid */\r\n");
                    sb.Append("      filterName: \"\", //查询实体\r\n");
                    sb.Append("      tableData: [], //表格实体\r\n");
                    sb.Append("      //工具栏配置\r\n");
                    sb.Append("      tableToolbar: {\r\n");
                    sb.Append("        export: true,\r\n");
                    sb.Append("        refresh: { \r\n");
                    sb.Append("          query : ()=> {\r\n");
                    sb.Append("            this.filterName = ''; //清空条件\r\n");
                    sb.Append("            this.query();\r\n");
                    sb.Append("          }\r\n");
                    sb.Append("        },\r\n");
                    sb.Append("        zoom: true,\r\n");
                    sb.Append("        custom: true\r\n");
                    sb.Append("      },\r\n");
                    sb.Append("      /* 实体数据 */\r\n");
                    sb.Append("    };\r\n");
                    sb.Append("  },\r\n");
                    sb.Append("  created() {\r\n");
                    sb.Append("    //初始化\r\n");
                    sb.Append("    this.init();\r\n");
                    sb.Append("  },\r\n");
                    sb.Append("  methods: {\r\n");
                    sb.Append(init);
                    sb.Append("    //列表数据\r\n");
                    sb.Append("    query() {\r\n");
                    sb.Append("      this.$store.commit(\"SET_ISLOADING\", true);\r\n");
                    sb.Append($"      return {config.AppDomain}.");
                    if (isTree)
                    {
                        sb.Append("GetTreeList({queryjson:JSON.stringify({QueryInfo:this.filterName})})");
                    }
                    else
                    {
                        sb.Append("GetList({queryjson:JSON.stringify({QueryInfo:this.filterName})})");
                    }
                    sb.Append(".then(res => {\r\n");
                    sb.Append("          this.tableData = res;\r\n");
                    sb.Append("          this.$store.commit(\"SET_ISLOADING\",false);\r\n");
                    sb.Append("        })\r\n");
                    sb.Append("    },\r\n");
                    sb.Append(changeState);
                    sb.Append(curd);
                    sb.Append("  }\r\n");
                    sb.Append("} \r\n");
                    sb.Append("</script>\r\n");
                    #endregion
                }

                #region 代码生成
                if (isGenerate && !config.FontSrcPath.IsEmpty())
                {
                    //输出文件全路径
                    string _contentDir = config.FontSrcPath + Path.DirectorySeparatorChar + "views" + Path.DirectorySeparatorChar + config.Module + Path.DirectorySeparatorChar + config.AppDomain + Path.DirectorySeparatorChar + "Index.vue";
                    DirFileHelper.CreateFileContent(_contentDir, sb.ToString());
                }
                #endregion

                res.Append(sb);
            }
            return res.ToString();
        }
        #endregion

        #region 表单 
        /// <summary>
        /// 表单代码
        /// TODO: FieldType、FieldRule字段类型扩充
        /// </summary>
        /// <param name="config"></param>
        /// <param name="isGenerate"></param>
        /// <returns></returns>
        public string FormCode(CodeBaseConfigModel config, bool isGenerate)
        {
            StringBuilder res = new StringBuilder(200);
            foreach (var item in config.TableNames)
            {
                StringBuilder sb = new StringBuilder(200);
                //帕斯卡命名转换
                string tableName = item.Pascalize();
                //根据表名获取表和表字段信息
                var table = this.BaseRepository.GetDBTable<DatabaseTableModel>()?.FirstOrDefault(c => c.name.Equals(tableName, StringComparison.OrdinalIgnoreCase));

                #region 表单配置
                StringBuilder form = new StringBuilder(200);
                foreach (var field in config.FieldList)
                {
                    if (field.ShowForm)
                    {
                        form.Append($"          <vxe-form-item title=\"{field.Remark}\" field=\"{field.Name}\">\r\n");
                        switch (field.FieldType)
                        {
                            case FieldType.DateTime:
                                form.Append($"            <rayd-date-picker type=\"date\" v-model=\"formEntity.{field.Name}\" />\r\n");
                                break;
                            case FieldType.Integer:
                                form.Append($"          <el-input-number :controls=\"false\" :min=\"0\" v-model=\"formEntity.{field.Name}\"></el-input-number>\r\n");
                                break;
                            case FieldType.Float:
                                form.Append($"          <el-input-number :controls=\"false\" :precision=\"2\" :min=\"0\" v-model=\"formEntity.{field.Name}\"></el-input-number>\r\n");
                                break;
                            case FieldType.TextArea:
                                form.Append("          <el-input\r\n");
                                form.Append("              type=\"textarea\"\r\n");
                                form.Append("              :autosize=\"{ minRows: 4, maxRows: 4}\"\r\n");
                                form.Append("              maxlength=\"50\"\r\n");
                                form.Append("              show-word-limit\r\n");
                                form.Append("              placeholder=\"请输入\"\r\n");
                                form.Append("              clearable\r\n");
                                form.Append($"              v-model=\"formEntity.{field.Name}\"\r\n");
                                form.Append("          ></el-input>\r\n");
                                break;
                            case FieldType.File:
                                form.Append($"          <rayd-file :isRead=\"false\" :removable=\"true\" :multiple=\"true\" :folderId=\"{field.Name}\" />\r\n");
                                break;
                            case FieldType.Image:
                                form.Append($"          <rayd-image-upload v-model=\"{field.Name}\" />\r\n");
                                break;
                            default:
                                form.Append($"            <el-input v-model=\"formEntity.{field.Name}\" placeholder=\"请输入\" clearable></el-input>\r\n");
                                break;
                        }
                        form.Append("          </vxe-form-item>\r\n");
                    }
                }
                #endregion

                #region 规则配置
                StringBuilder rule = new StringBuilder(200);
                foreach (var field in config.FieldList)
                {
                    switch (field.FieldRule)
                    {
                        case FieldRule.Required:
                            rule.Append($"        {field.Name}: [{{ required: true, message: \"请输入{field.Remark}!\" }}],\r\n");
                            break;
                        case FieldRule.Number: break;
                        default: break;
                    }
                }
                #endregion

                #region Template
                sb.Append("<template>\r\n");
                sb.Append("  <vxe-modal\r\n");
                sb.Append("    resize\r\n");
                sb.Append("    esc-closable\r\n");
                sb.Append("    width=\"55%\"\r\n");
                sb.Append("    height=\"80%\"\r\n");
                sb.Append("    showFooter\r\n");
                sb.Append("    v-model=\"formVisible\"\r\n");
                sb.Append("    @hide=\"formClose\"\r\n");
                sb.Append("    :loading=\"formLoading\"\r\n");
                sb.Append("    destroy-on-close\r\n");
                sb.Append("  >\r\n");
                sb.Append("    <template slot=\"title\">\r\n");
                sb.Append($"      <span>{table.tdescription}表单</span>\r\n");
                sb.Append("    </template>\r\n");
                sb.Append("    <template>\r\n");
                sb.Append("      <el-scrollbar class=\"scrollbar-handle\">\r\n");
                sb.Append("	       <!-- 主体 -->\r\n");
                sb.Append("        <vxe-form\r\n");
                sb.Append("          title-width=\"100\"\r\n");
                sb.Append("          title-align=\"right\"\r\n");
                sb.Append("          :data=\"formEntity\"\r\n");
                sb.Append("          :rules=\"rules\"\r\n");
                sb.Append("          span=\"12\"\r\n");
                sb.Append("        >\r\n");
                sb.Append(form);
                sb.Append("        </vxe-form>\r\n");
                sb.Append("      </el-scrollbar>\r\n");
                sb.Append("    </template>\r\n");
                sb.Append("    <template slot=\"footer\">\r\n");
                sb.Append("      <el-button type=\"primary\" v-form-validate=\"formSubmit\">保存</el-button>\r\n");
                sb.Append("      <el-button @click=\"formVisible=false\">取消</el-button>\r\n");
                sb.Append("    </template>\r\n");
                sb.Append("  </vxe-modal>\r\n");
                sb.Append("</template>\r\n\r\n");
                #endregion

                #region Script
                sb.Append("<script>\r\n");
                sb.Append($"import {{ {config.AppDomain} }} from \"@/api\";\r\n");
                sb.Append("export default {\r\n");
                sb.Append("  props: {\r\n");
                sb.Append("  },\r\n");
                sb.Append("  data() {\r\n");
                sb.Append("    return {\r\n");
                sb.Append("      //表单可见\r\n");
                sb.Append("      formVisible: false,\r\n");
                sb.Append("      //表单加载中\r\n");
                sb.Append("      formLoading: false,\r\n");
                sb.Append("      //表单实体\r\n");
                sb.Append("      formEntity: {},\r\n");
                sb.Append("      //表单验证规则（规则键必须和表单键一致）\r\n");
                sb.Append("      rules: {\r\n");
                sb.Append(rule);
                sb.Append("      },\r\n");
                sb.Append("      /* 实体数据 */\r\n");
                sb.Append("    };\r\n");
                sb.Append("  },\r\n");
                sb.Append("  created() {\r\n");
                sb.Append("    //初始化\r\n");
                sb.Append("    this.init();\r\n");
                sb.Append("  },\r\n");
                sb.Append("  methods: {\r\n");
                sb.Append("    //初始化\r\n");
                sb.Append("    init() {\r\n");
                sb.Append("      /* 初始化数据源 */\r\n");
                sb.Append("      Promise.all([]).then(() => {});\r\n");
                sb.Append("    },\r\n");
                sb.Append("    //表单开启\r\n");
                sb.Append("    formOpen(row) {\r\n");
                sb.Append("      this.formVisible = this.formLoading = true;   //打开表单\r\n");
                sb.Append("      if (!row) {\r\n");
                sb.Append("        //新增\r\n");
                sb.Append("      } else {\r\n");
                sb.Append("        //编辑\r\n");
                sb.Append("        this.formEntity = JSON.parse(JSON.stringify(row));\r\n");
                sb.Append("      }\r\n");
                sb.Append("      this.formLoading = false;\r\n");
                sb.Append("    },\r\n");
                sb.Append("    //表单提交\r\n");
                sb.Append("    formSubmit() {\r\n");
                sb.Append($"      {config.AppDomain}.Save(this.formEntity).then(res => {{\r\n");
                sb.Append("        this.formVisible = false; //关闭弹窗\r\n");
                sb.Append("        this.$emit(\"refresh\"); //刷新表格\r\n");
                sb.Append("      });\r\n");
                sb.Append("    },\r\n");
                sb.Append("    //表单关闭\r\n");
                sb.Append("    formClose() {\r\n");
                sb.Append("      //清除表单验证\r\n");
                sb.Append("      this.util.formClearValid();\r\n");
                sb.Append("      //数据归位\r\n");
                sb.Append("      Object.assign(this.$data, this.$options.data.call(this));\r\n");
                sb.Append("    }\r\n");
                sb.Append("  }\r\n");
                sb.Append("}; \r\n");
                sb.Append("</script>\r\n");
                #endregion

                #region 代码生成
                if (isGenerate && !config.FontSrcPath.IsEmpty())
                {
                    //输出文件全路径
                    string _contentDir = config.FontSrcPath + Path.DirectorySeparatorChar + "views" + Path.DirectorySeparatorChar + config.Module + Path.DirectorySeparatorChar + config.AppDomain + Path.DirectorySeparatorChar + "Form.vue";
                    DirFileHelper.CreateFileContent(_contentDir, sb.ToString());
                }
                #endregion

                res.Append(sb);
            }
            return res.ToString();
        }
        #endregion

        #region 写入api.js文件
        /// <summary>
        /// API资源写入文件
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public (bool, string) WriteApi(CodeBaseConfigModel config)
        {
            //api.js文件全路径
            string apiPath = config.FontSrcPath + Path.DirectorySeparatorChar + "api" + Path.DirectorySeparatorChar + "index.js";
            if (DirFileHelper.IsExistFile(apiPath))
            {
                foreach (var item in config.TableNames)
                {
                    StringBuilder sb = new StringBuilder(200);
                    //根据表名获取表信息
                    var table = this.BaseRepository.GetDBTable<DatabaseTableModel>()?.FirstOrDefault(c => c.name.Equals(item, StringComparison.OrdinalIgnoreCase));
                    //是否为树型结构
                    bool isTree = (config.IsTree && config.FieldList.Exists(c => c.FieldStatistical.Equals(FieldStatistical.ParentId)));
                    //是否存在使能标志
                    var EnabledMarkField = config.FieldList.Find(c => c.FieldStatistical.Equals(FieldStatistical.EnabledMark));
                    bool isEnabledMark = !EnabledMarkField.IsEmpty();

                    sb.Append("\r\n");
                    sb.Append($"//{table.tdescription}资源\r\n");
                    sb.Append($"export const {config.AppDomain} = {{\r\n");
                    #region 获取
                    if (config.IsPage)
                    {
                        sb.Append("    GetPageList: (params) => {\r\n");
                        sb.Append($"        return http.get(\"/{config.Area.ToLower()}Api/{config.AppDomain}/GetPageList\", params);\r\n");
                        sb.Append("    },\r\n");
                    }
                    else
                    {
                        if (isTree)
                        {
                            sb.Append("    GetTreeList: (params, removeId) => {\r\n");
                            sb.Append($"        return http.getTree(\"/{config.Area.ToLower()}Api/{config.AppDomain}/GetTreeList\", {{ queryjson: params }}, removeId);\r\n");
                            sb.Append("    },\r\n");
                        }
                        else
                        {
                            sb.Append("    GetList: (params) => {\r\n");
                            sb.Append($"        return http.get(\"/{config.Area.ToLower()}Api/{config.AppDomain}/GetList\", {{ queryjson: params }});\r\n");
                            sb.Append("    },\r\n");
                        }
                    }
                    #endregion
                    #region 删除
                    sb.Append("    Delete: (params) => {\r\n");
                    sb.Append($"        return http.put(\"/{config.Area.ToLower()}Api/{config.AppDomain}/DeleteForm\", params);\r\n");
                    sb.Append("    },\r\n");
                    #endregion
                    #region 保存
                    sb.Append("    Save: (params) => {\r\n");
                    sb.Append($"        return http.put(\"/{config.Area.ToLower()}Api/{config.AppDomain}/SaveForm\", params);\r\n");
                    sb.Append("    },\r\n");
                    #endregion
                    #region 验证
                    sb.Append("    ValidateExist: (params) => {\r\n");
                    sb.Append($"        return http.get(\"/{config.Area.ToLower()}Api/{config.AppDomain}/ValidateExist\", params);\r\n");
                    sb.Append("    },\r\n");
                    #endregion
                    #region 状态变更
                    if (isEnabledMark)
                    {
                        sb.Append("    ChangeState: (params) => {\r\n");
                        sb.Append($"        return http.put(\"/{config.Area.ToLower()}Api/{config.AppDomain}/ChangeState\", params);\r\n");
                        sb.Append("    },\r\n");
                    }
                    #endregion
                    sb.Append("}\r\n");

                    //写入文件
                    DirFileHelper.AppendText(apiPath, sb.ToString());
                }
                return (true, "写入成功！");
            }
            return (false, "找不到前端项目源文件, 请确保路径配置正确！");
        }
        #endregion

        #region 生成模块菜单
        /// <summary>
        /// 生成模块菜单
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public (bool, string) GenerateModule(CodeBaseConfigModel config)
        {
            //补齐导航地址
            config.ModuleEntity.B_UrlAddress = $"/{config.Module}/{config.AppDomain}/Index";
            //模块按钮
            List<ModuleButtonEntity> list = new List<ModuleButtonEntity>();
            list.Add(new ModuleButtonEntity()
            {
                B_EnCode = "Add",
                B_FullName = "新增",
                B_SortCode = 0
            });
            list.Add(new ModuleButtonEntity()
            {
                B_EnCode = "Edit",
                B_FullName = "编辑",
                B_SortCode = 0
            });
            list.Add(new ModuleButtonEntity()
            {
                B_EnCode = "Delete",
                B_FullName = "删除",
                B_SortCode = 0
            });
            return _module.SaveForm(config.ModuleEntity, list);
        }
        #endregion

        #region MyRegion
        public string MapCsharpType(string dbtype)
        {
            if (string.IsNullOrEmpty(dbtype)) return dbtype;
            dbtype = dbtype.ToLower();
            string csharpType = "object";
            switch (dbtype)
            {
                //MSSQL
                case "bigint": csharpType = "long"; break;
                case "binary": csharpType = "byte[]"; break;
                case "bit": csharpType = "bool"; break;
                case "char": csharpType = "string"; break;
                case "date": csharpType = "DateTime"; break;
                case "datetime": csharpType = "DateTime"; break;
                case "datetime2": csharpType = "DateTime"; break;
                case "datetimeoffset": csharpType = "DateTimeOffset"; break;
                case "decimal": csharpType = "decimal"; break;
                case "float": csharpType = "float"; break;
                case "image": csharpType = "byte[]"; break;
                case "int": csharpType = "int"; break;
                case "money": csharpType = "decimal"; break;
                case "nchar": csharpType = "string"; break;
                case "ntext": csharpType = "string"; break;
                case "numeric": csharpType = "decimal"; break;
                case "nvarchar": csharpType = "string"; break;
                case "real": csharpType = "Single"; break;
                case "smalldatetime": csharpType = "DateTime"; break;
                case "smallint": csharpType = "short"; break;
                case "smallmoney": csharpType = "decimal"; break;
                case "sql_variant": csharpType = "object"; break;
                case "sysname": csharpType = "object"; break;
                case "text": csharpType = "string"; break;
                case "time": csharpType = "TimeSpan"; break;
                case "tinyint": csharpType = "byte"; break;
                case "uniqueidentifier": csharpType = "Guid"; break;
                case "varbinary": csharpType = "byte[]"; break;
                case "varchar": csharpType = "string"; break;
                case "xml": csharpType = "string"; break;
                //Oracle
                case "number": csharpType = "int"; break;
                case "nvarchar2":
                case "varchar2":
                case "clob": csharpType = "string"; break;
                //MySql
                case "mediumint":
                case "integer": csharpType = "int"; break;
                case "double": csharpType = "double"; break;
                case "year":
                case "timestamp": csharpType = "DateTime"; break;
                case "tinyblob":
                case "blob":
                case "mediumblob":
                case "longblog": csharpType = "byte[]"; break;
                case "tinytext":
                case "mediumtext":
                case "longtext": csharpType = "string"; break;

                default: csharpType = "object"; break;
            }
            return csharpType;
        }
        public Type MapCommonType(string dbtype)
        {
            if (string.IsNullOrEmpty(dbtype)) return Type.Missing.GetType();
            dbtype = dbtype.ToLower();
            Type commonType = typeof(object);
            switch (dbtype)
            {
                //MSSQL
                case "bigint": commonType = typeof(long); break;
                case "binary": commonType = typeof(byte[]); break;
                case "bit": commonType = typeof(bool); break;
                case "char": commonType = typeof(string); break;
                case "date": commonType = typeof(DateTime); break;
                case "datetime": commonType = typeof(DateTime); break;
                case "datetime2": commonType = typeof(DateTime); break;
                case "datetimeoffset": commonType = typeof(DateTimeOffset); break;
                case "decimal": commonType = typeof(decimal); break;
                case "float": commonType = typeof(float); break;
                case "image": commonType = typeof(byte[]); break;
                case "int": commonType = typeof(int); break;
                case "money": commonType = typeof(decimal); break;
                case "nchar": commonType = typeof(string); break;
                case "ntext": commonType = typeof(string); break;
                case "numeric": commonType = typeof(decimal); break;
                case "nvarchar": commonType = typeof(string); break;
                case "real": commonType = typeof(Single); break;
                case "smalldatetime": commonType = typeof(DateTime); break;
                case "smallint": commonType = typeof(short); break;
                case "smallmoney": commonType = typeof(decimal); break;
                case "sql_variant": commonType = typeof(object); break;
                case "sysname": commonType = typeof(object); break;
                case "text": commonType = typeof(string); break;
                case "time": commonType = typeof(TimeSpan); break;
                case "tinyint": commonType = typeof(byte); break;
                case "uniqueidentifier": commonType = typeof(Guid); break;
                case "varbinary": commonType = typeof(byte[]); break;
                case "varchar": commonType = typeof(string); break;
                case "xml": commonType = typeof(string); break;
                //Oracle
                case "number": commonType = typeof(int); break;
                case "nvarchar2":
                case "varchar2":
                case "clob": commonType = typeof(string); break;
                //MySql
                case "mediumint":
                case "integer": commonType = typeof(int); break;
                case "double": commonType = typeof(double); break;
                case "year":
                case "timestamp": commonType = typeof(DateTime); break;
                case "tinyblob":
                case "blob":
                case "mediumblob":
                case "longblog": commonType = typeof(byte[]); break;
                case "tinytext":
                case "mediumtext":
                case "longtext": commonType = typeof(string); break;

                default: commonType = typeof(object); break;
            }
            return commonType;
        }
        #endregion
    }
}

